/*
 * Copyright (c) 2012 Robert Burrell Donkin robertburrelldonkin.name
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 */
package walrus.app;

import java.io.File;
import java.util.Date;

import walrus.base.ArticleProcessor;
import walrus.base.Constants;
import walrus.engine.ArticleProcessingEngine;
import walrus.unpack.xml.QueuingArticleLoader;

public abstract class WikiProcessor {

	private final String pathname;
	
	private int threads = Constants.DEFAULT_NUMBER_OF_THREADS;
	private int buffers = Constants.DEFAULT_NUMBER_OF_BUFFERS;
	
	public WikiProcessor(String pathname) {
		super();
		this.pathname = pathname;
	}

	public int getThreads() {
		return threads;
	}

	public WikiProcessor setThreads(int threads) {
		this.threads = threads;
		return this;
	}

	public int getBuffers() {
		return buffers;
	}

	public WikiProcessor setBuffers(int buffers) {
		this.buffers = buffers;
		return this;
	}

	public void perform() throws Exception {
    	long start = System.currentTimeMillis();
    	System.out.println("Started " + now());
    	final ArticleProcessor processor = createProcessor();
		ArticleProcessingEngine engine = new ArticleProcessingEngine(processor, buffers, threads);
    	new Thread(engine).start();
		new QueuingArticleLoader(new File(pathname), engine.getOut(), engine.getIn()).load();
    	long end = System.currentTimeMillis();
    	System.out.println("Ended " + now());
    	System.out.println("Duration " + (end - start)/1000f + " (secs)");
    	engine.finish();
    	engine.waitTillfinished();
    	processor.close();
	}


	@SuppressWarnings("deprecation")
	private String now() {
		return new Date().toGMTString();
	}
	
	protected abstract ArticleProcessor createProcessor();
}